<!--
* @Description: 描述
* @Author: ZHe
* @Date: 2022/01/01
* @params:
  {
  }
* @func:
-->
<script lang="jsx">
	import { globalStore } from '@/store'
	import tool from '@/utils/tool'
	import customerQwOrderApi from '@/api/biz/customerQwOrderApi'
	import fileApi from '@/api/dev/fileApi'

	const store = globalStore()

	// 录入项
	const EntryItems = {
		props: ['module', 'modelValue'],
		emits: ['update:modelValue'],
		data() {
			return {}
		},
		computed: {
			datePickerVal: {
				get() {
					return this.modelValue
				},
				set(val) {
					this.emitValue(val)
				}
			}
		},
		methods: {
			// 更新值
			emitValue(value) {
				this.$emit('update:modelValue', value)
			},
			// 渲染组件
			renderEl({ attrs }) {
				switch (this.module) {
					case 'Input':
						return (
							<el-input
								style="width:360px"
								placeholder="请输入"
								{...attrs}
								modelValue={this.modelValue}
								onInput={(val) => this.emitValue(val)}></el-input>
						)
					case 'InputNumber':
						return (
							<el-input
								style="width:360px"
								{...attrs}
								modelValue={this.modelValue}
								onInput={(val) => {
									this.emitValue(
										val
											.replace(/[^\d.]/g, '')
											.replace('.', '$#$')
											.replace(/\./g, '')
											.replace('$#$', '.')
											.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
											.replace(/^\./g, '')
									)
								}}></el-input>
						)
					case 'Textarea':
						return (
							<el-input
								style="width:98%"
								placeholder="请输入"
								{...attrs}
								type="textarea"
								row={2}
								modelValue={this.modelValue}
								onInput={(val) => this.emitValue(val)}></el-input>
						)
					case 'Select':
						return (
							<el-select
								style="width:360px"
								placeholder="请选择"
								{...attrs}
								modelValue={this.modelValue}
								onChange={(val) => {
									this.emitValue(val)
									attrs.bindObject && attrs.bindObject(attrs.option.find((item) => item.value === val))
								}}>
								{attrs.option && attrs.option.length
									? attrs.option.reduce((total, o, i) => {
											if (o.value !== undefined) {
												total.push(<el-option key={i} label={o.label} value={o.value} />)
											}
											return total
									  }, [])
									: null}
							</el-select>
						)
					case 'DatePicker':
						return (
							<el-date-picker
								style="width:98%"
								placeholder="选择日期"
								type="date"
								value-format="YYYY-MM-DD"
								{...attrs}
								v-model={this.datePickerVal}
							/>
						)
					case 'ClickSelect':
						return (
							<div
								class="el-input el-input--small"
								style="width:360px;
	   								border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
									box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;"
								data-capture="true">
								<div
									class="el-input__inner"
									style={[
										attrs.disabled
											? 'background-color: #F5F7FA;color: #C0C4CC;cursor: not-allowed;'
											: 'cursor: pointer;',
										{ height: '30px', lineHeight: '27px', border: '1px solid #DDD', borderRadius: '2px' }
									]}
									data-capture="true"
									onClick={(e) => {
										if (attrs.disabled) e.stopPropagation()
									}}>
									{this.modelValue ? (
										<span
											style={['padding-left: 12px; font-size: 14px', { color: attrs.disabled ? '#AAA' : '#333' }]}
											data-capture="true">
											{this.modelValue}
										</span>
									) : (
										<span style="padding-left: 12px;color:#AAA;font-size: 14px" data-capture="true">
											请选择
										</span>
									)}
								</div>
							</div>
						)
					case 'Cascader':
						return (
							<el-cascader
								placeholder="请选择"
								ref="cascaderRef"
								style="width:98%;"
								filterable
								modelValue={this.modelValue}
								options={attrs.option}
								disabled={attrs.disabled}
								onChange={(val) => {
									this.emitValue(val)
									this.$refs.cascaderRef &&
										attrs.bindObject &&
										attrs.bindObject(
											val
												? {
														label: this.$refs.cascaderRef.getCheckedNodes()[0].pathLabels,
														value: val
												  }
												: null
										)
								}}></el-cascader>
						)
					default:
						return null
				}
			}
		},
		render() {
			return this.renderEl({ attrs: this.$attrs })
		}
	}

	const ElRow = {
		render() {
			return <el-row {...this.$attrs}>{this.$slots.default()}</el-row>
		}
	}

	const ElCol = {
		render() {
			return <el-col {...this.$attrs}>{this.$slots.default()}</el-col>
		}
	}

	// 商品与金额
	const initDataService = () => ({
		business: null,
		businessCodeDetailId: null, // 业务代码id3级
		businessCodeDetailName: null,
		businessCodeId: null, // 业务代码2级id
		businessCodeName: null,
		businessDiskId: null, // 业务盘1级id
		businessDiskName: null,
		businessPrice: null,
		cost: null,
		isHideAccount: true, // 控制显隐
		accountMonth: null,
		accountProperties: null,
		accountCityId: null,
		accountCity: null,
		orderSalesman: [
			{
				userId: null,
				userName: null,
				achievement: null
			}
		]
	})

	// 线索分润人
	const initDataClueDivider = () => ({
		cluesShareId: null,
		cluesShareName: null,
		cluesShareAchievement: null
	})

	export default {
		components: {
			ElRow,
			ElCol,
			EntryItems
		},
		props: {
			// 合同信息
			contractInfo: {
				type: Object,
				default: () => ({})
			}
		},
		emits: ['finished'],
		data() {
			return {
				formData: {
					depart: null,
					departObj: null,
					receiveTitle: null,

					type: null,
					contractWay: null,
					orderSourceId: null,
					orderSourceName: null,
					cluesSourcesId: null,
					cluesSourcesName: null,

					activityId: null,
					activityName: null,
					preferential: null,
					frontMoney: null,
					beforeSalesperson: null,
					introducerCompany: null,
					accountDept: null,
					resourceMonth: null,
					beforeRenewMoney: null,
					beforeRenewMonth: null,
					tags: null,
					remark: null,
					orderDetail: [initDataService()],
					clueDivider: [initDataClueDivider()],
					id: null,
					customerName: null,

					// 附件
					imgId: {},
					customerMobile: null,
					resourceDate: null, // 资源日期
					year: null,
					month: null,
					day: null,
					orderNo: null
				},
				rules: {
					depart: { required: true, message: '不能为空', trigger: 'blur' },
					receiveTitle: { required: true, message: '不能为空', trigger: 'blur' },
					business: { required: true, message: '不能为空', trigger: 'blur' },
					businessPrice: { required: true, message: '不能为空', trigger: 'blur' },
					accountMonth: { required: true, message: '不能为空', trigger: 'blur' },
					accountProperties: { required: true, message: '不能为空', trigger: 'blur' },
					accountCityId: { required: true, message: '不能为空', trigger: 'blur' },
					type: { required: true, message: '不能为空', trigger: 'blur' },
					contractWay: { required: true, message: '不能为空', trigger: 'blur' },
					orderSourceId: { required: true, message: '不能为空', trigger: 'blur' },
					cluesSourcesName: { required: true, message: '不能为空', trigger: 'blur' },
					cluesSourcesId: { required: true, message: '不能为空', trigger: 'blur' },
					cluesShareName: { required: true, message: '不能为空', trigger: 'blur' },
					cluesShareAchievement: { required: true, message: '不能为空', trigger: 'blur' },
					customerMobile: { required: true, message: '不能为空', trigger: 'blur' },
					resourceDate: { required: true, message: '不能为空', trigger: 'blur' },
					beforeSalesperson: { required: true, message: '不能为空', trigger: 'blur' },
					introducerCompany: { required: true, message: '不能为空', trigger: 'blur' },
					accountDept: { required: true, message: '不能为空', trigger: 'blur' },
					resourceMonth: { required: true, message: '不能为空', trigger: 'blur' },
					beforeRenewMoney: { required: true, message: '不能为空', trigger: 'blur' },
					beforeRenewMonth: { required: true, message: '不能为空', trigger: 'blur' },
					activityId: { required: true, message: '不能为空', trigger: 'blur' },
					preferential: { required: true, message: '不能为空', trigger: 'blur' },
					frontMoney: { required: true, message: '不能为空', trigger: 'blur' },
					year: { required: true, message: '不能为空', trigger: 'blur' },
					month: { required: true, message: '不能为空', trigger: 'blur' },
					day: { required: true, message: '不能为空', trigger: 'blur' },
					orderNo: { required: true, message: '不能为空', trigger: 'blur' }
				},
				// 下拉数据
				departmentOption: [],
				paymentOption: [],
				businessOption: [],
				accountPropertiesOption: [],
				accountCityOption: [],
				typeOption: [],
				contractWayOption: [],
				orderSourceOption: [],
				cluesSourcesOption: [],
				activityOption: [],
				isNoOption: [],
				frontMoneyOption: [],
				tagsOption: [],

				visible: false,

				// 附件
				// 凭证附件
				fileList: [],
				acceptFileType: [
					// jpg
					'image/jpg',
					'image/jpeg',
					// png
					'image/png'
				],
				maxFileSize: 500, // kb

				// 预览相关
				showViewer: false,
				initialIndex: 0,
				previewSrcList: [],

				// 选人
				checkedIndex: null,
				checkedStaff: [],
				visibleStaff: false
			}
		},
		computed: {
			isEdit() {
				return this.formData.id ? true : false
			},
			contractId() {
				return this.contractInfo.id
			},
			isRelationQW() {
				// 是否已关联企微
				return store.userInfo.id
			},
			hideAttrs() {
				const isHideCluesSources = !(this.formData.orderSourceId == 270)
				const isHidePhoneAndDate = !(
					[308, 320, 331, 346, 401, 402, 472, 473, 498].includes(this.formData.orderSourceId) ||
					(this.formData.orderSourceId >= 271 && this.formData.orderSourceId <= 281) ||
					(this.formData.orderSourceId >= 297 && this.formData.orderSourceId <= 299)
				)
				const isHideClueDivider = !(
					this.formData.orderSourceId == 270 &&
					this.formData.orderDetail.some((item) => item.businessCodeDetailId == 194)
				)
				const isHideYMD = !(this.formData.frontMoney === '3')
				const isHideBeforeSalesperson = !['2', '3', '4'].includes(this.formData.type)
				const isHideIntroducerCompany = !['2', '3'].includes(this.formData.type)
				const isHideAccountDept = !['4'].includes(this.formData.type)

				return {
					isHideCluesSources,
					isHidePhoneAndDate,
					isHideClueDivider,
					isHideYMD,
					isHideBeforeSalesperson,
					isHideIntroducerCompany,
					isHideAccountDept
				}
			}
		},
		watch: {},
		async created() {
			if (!this.isRelationQW) return

			this.canuseBusinessCode = [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 365, 366, 367, 497]

			this.accountPropertiesOption = [
				{ label: '小规模', value: '小规模' },
				{ label: '小规模0报', value: '小规模0报' },
				{ label: '一般', value: '一般' },
				{ label: '一般0报', value: '一般0报' }
			]
			this.typeOption = [
				{ label: '新签', value: '1' },
				{ label: '二次消费', value: '2' },
				{ label: '转介绍', value: '3' },
				{ label: '续费', value: '4' }
			]
			this.contractWayOption = [
				{ label: '线上网签', value: '1' },
				{ label: '线下面签', value: '2' }
			]
			this.isNoOption = [
				{ label: '是', value: '1' },
				{ label: '否', value: '2' }
			]
			this.frontMoneyOption = [
				{ label: '全款', value: '1' },
				{ label: '定金', value: '2' },
				{ label: '尾款', value: '3' }
			]

			// 获取基础
			Promise.all([
				this.getBaseData('getConfigByType', { type: 'business' }),
				this.getBaseData('getConfigByType', { type: 'company' }),
				this.getBaseData('getConfigByType', { type: 'city' }),
				this.getBaseData('getConfigByType', { type: 'orders' }),
				this.getBaseData('getConfigByType', { type: 'package' }),
				this.getBaseData('getConfigByType', { type: 'tags' }),
				this.getBaseData('getOrderUserInfo', { userId: store.userInfo.id })
			]).then((resArr) => {
				this.businessOption = tool.analyticTree(resArr[0])
				this.paymentOption = resArr[1]
				this.accountCityOption = resArr[2]
				this.orderSourceOption = resArr[3]
				this.activityOption = resArr[4]
				this.tagsOption = resArr[5].map((item) => ({ label: item.label, value: item.label }))
				this.departmentOption = resArr[6].map((item) => {
					return {
						label: [item.division, item.center, item.team, item.department, item.sonDepartment]
							.filter((child) => child)
							.join('/'),
						value: [item.dept1, item.dept2, item.dept3, item.dept4, item.dept5].filter((child) => child).join(','),
						objOption: item
					}
				})
			})

			// 获取详情
			const data = await customerQwOrderApi.getQywxOrderInfo({ contractId: this.contractId })

			if (data) {
				Object.keys(this.formData).forEach((key) => {
					this.formData[key] = data[key]
				})

				// 额外处理
				// 部门
				// this.formData.depart = [data.dept1, data.dept2, data.dept3, data.dept4, data.dept5]
				// 	.filter((child) => child)
				// 	.join(',')
				// 解决线上，下拉接口数据无对应匹配不上的问题
				this.formData.depart = [data.division, data.center, data.team, data.department, data.sonDepartment]
					.filter((child) => child)
					.join('/')
				// 收款抬头
				this.formData.receiveTitle = Number(data.receiveTitle)

				// 服务项目与分润人
				this.formData.orderDetail.forEach((item) => {
					const orderSalesman = data.orderSalesman.filter(
						(child) => item.businessCodeDetailId == child.businessCodeDetailId
					)
					item.orderSalesman = orderSalesman
					item.business = [item.businessDiskId, item.businessCodeId, item.businessCodeDetailId]
					item.isHideAccount = !this.canuseBusinessCode.includes(item.businessCodeDetailId)
				})

				// 线索分润人
				if (data.cluesShareId && data.cluesShareId !== '') {
					this.formData.clueDivider = []
					const cluesShareAchievement = data.cluesShareAchievement.split(',')
					const cluesShareId = data.cluesShareId.split(',')
					const cluesShareName = data.cluesShareName.split(',')
					cluesShareId.forEach((item, index) => {
						this.formData.clueDivider.push({
							cluesShareAchievement: cluesShareAchievement[index],
							cluesShareId: cluesShareId[index],
							cluesShareName: cluesShareName[index]
						})
					})
				}

				// 年、月、日、单号
				if (data.frontMoneyOrderNo && data.frontMoneyOrderNo !== '') {
					const front = data.frontMoneyOrderNo.split(',')
					this.formData.year = front[0]
					this.formData.month = front[1]
					this.formData.day = front[2]
					this.formData.orderNo = front[3]
				}

				// 亮点
				if (data.tags) this.formData.tags = data.tags.split(',')

				// 附件
				this.setFileValue(data.picture)
			}

			// 默认值
			if (!this.isEdit) {
				// 获取默认
				this.getBaseData('getPerformanceInformation', { customerCode: this.contractInfo.customerCode }).then((d) => {
					this.formData.beforeSalesperson = d.originalSaleName
					this.formData.beforeRenewMoney = d.beforeAccountAmount
					this.formData.beforeRenewMonth = d.beforeAccountMonth
				})

				// 收款方式、备注
				this.formData.frontMoney = this.contractInfo.paymentMethod === 'DEPOSIT' ? '2' : '1'
				this.formData.remark = this.contractInfo.remark

				// 关联客户
				this.formData.customerName = this.contractInfo.firstParty

				// 附件
				this.setFileValue(this.contractInfo.voucherImg)

				document.querySelector('.customsDeclaration-component').addEventListener('scroll', this.onPopoverScroll)
			}
		},
		beforeUnmount() {
			document.querySelector('.customsDeclaration-component').removeEventListener('scroll', this.onPopoverScroll)
		},
		methods: {
			// 添加项
			addItem(arr, value) {
				arr.push(value)
			},
			// 删除项
			deleteItem(arr, index) {
				arr.splice(index, 1)
			},
			// 设置、获取分润人
			toOrderSalesman(index) {
				const obj = this.formData.orderDetail[index[0]].orderSalesman[index[1]]
				return {
					set: (value) => {
						obj.userName = value[0].name
						obj.userId = value[0].userId
					},
					get: () => {
						return obj.userName
							? {
									name: obj.userName,
									userId: obj.userId
							  }
							: null
					}
				}
			},
			// 设置、获取线索分润人
			toClueDivider(index) {
				const obj = this.formData.clueDivider[index[0]]
				return {
					set: (value) => {
						obj.cluesShareName = value[0].name
						obj.cluesShareId = value[0].userId
					},
					get: () => {
						return obj.cluesShareName
							? {
									name: obj.cluesShareName,
									userId: obj.cluesShareId
							  }
							: null
					}
				}
			},
			// 设置、获取线索来源
			toClueSource() {
				const obj = this.formData
				return {
					set: (value) => {
						obj.cluesSourcesName = value[0].name
						obj.cluesSourcesId = value[0].userId
					},
					get: () => {
						return obj.cluesSourcesName
							? {
									name: obj.cluesSourcesName,
									userId: obj.cluesSourcesId
							  }
							: null
					}
				}
			},

			// 接口
			async save() {
				// 检查
				await this.$refs.formRef.validate((valid, fields) => {
					if (valid) {
						if (Object.keys(this.formData.imgId).length === 0) {
							this.$message.warning('请上传付款明细！')
							return
						}
						const params = {
							createUserId: store.userInfo.id,
							contractId: this.contractId,
							...tool.deepClone(this.formData)
						}

						// 额外处理
						// 隐藏项
						const {
							isHideCluesSources,
							isHidePhoneAndDate,
							isHideClueDivider,
							isHideYMD,
							isHideBeforeSalesperson,
							isHideIntroducerCompany,
							isHideAccountDept
						} = this.hideAttrs
						if (isHideCluesSources) {
							delete params.cluesSourcesName
							delete params.cluesSourcesId
						}
						if (isHidePhoneAndDate) {
							delete params.customerMobile
							delete params.resourceDate
						}
						if (isHideBeforeSalesperson) {
							delete params.beforeSalesperson
						}
						if (isHideIntroducerCompany) {
							delete params.introducerCompany
						}
						if (isHideAccountDept) {
							delete params.accountDept
							delete params.resourceMonth
							delete params.beforeRenewMoney
							delete params.beforeRenewMonth
						}

						// 部门
						Object.keys(params.departObj).forEach((key) => {
							params[key] = params.departObj[key]
						})
						delete params.depart
						delete params.departObj

						// 服务项目与分润人
						let receiveTotalMoney = 0
						let costMoney = 0
						params.orderSalesman = []
						params.orderDetail.forEach((item) => {
							item.orderSalesman.forEach((child) => {
								if (!child.userName) return

								params.orderSalesman.push({
									...child,
									businessCodeDetailId: item.businessCodeDetailId
								})
							})
							delete item.orderSalesman

							if (item.isHideAccount) {
								item.accountMonth = null
								item.accountProperties = null
								item.accountCityId = null
								item.accountCity = null
							}
							receiveTotalMoney = tool.accAdd(item.businessPrice, receiveTotalMoney)
							costMoney = item.cost ? tool.accAdd(item.cost, costMoney) : costMoney
						})
						params.receiveTotalMoney = receiveTotalMoney
						params.totalAchievement = tool.accSubtr(receiveTotalMoney, costMoney)

						// 线索分润人
						if (!isHideClueDivider) {
							const cluesShareAchievement = []
							const cluesShareId = []
							const cluesShareName = []
							params.clueDivider.forEach((item) => {
								cluesShareAchievement.push(item.cluesShareAchievement)
								cluesShareId.push(item.cluesShareId)
								cluesShareName.push(item.cluesShareName)
							})
							params.cluesShareAchievement = cluesShareAchievement.join(',')
							params.cluesShareId = cluesShareId.join(',')
							params.cluesShareName = cluesShareName.join(',')
						}
						delete params.clueDivider

						// 年、月、日、单号
						params.frontMoneyOrderNo = ''
						if (!isHideYMD) {
							params.frontMoneyOrderNo = [params.year, params.month, params.day, params.orderNo].join(',')
						}
						delete params.year
						delete params.month
						delete params.day
						delete params.orderNo

						// 亮点
						if (params.tags) params.tags = params.tags.join(',')

						// 附件
						params.picture = Object.values(params.imgId).join(',')
						delete params.imgId

						customerQwOrderApi.saveQywxOrderInfo(params).then((res) => {
							this.$message.success('报单成功！')
							this.formData.id = 99 // 触发禁用
							this.$emit('finished')
						})
					} else {
						console.log('error submit!', fields)
					}
				})
			},
			// 获取配置
			getBaseData(target, params) {
				const requestFn = {
					getConfigByType: customerQwOrderApi.getConfigByType, // 报单配置
					getOrderUserInfo: customerQwOrderApi.getOrderUserInfo, // 部门
					getPerformanceInformation: customerQwOrderApi.getPerformanceInformation // 默认数据
				}[target]
				return requestFn(params)
			},

			// 附件
			/**
			 * 文件类型上传前回调
			 */
			beforeFileUploads(file) {
				if (!this.acceptFileType.includes(file.type)) {
					this.$message({
						message: '上传文件格式必须为' + this.tipsFileType,
						type: 'error'
					})
					return false
				}

				const isLt500kb = file.size / 1024 < this.maxFileSize
				if (!isLt500kb) {
					this.$message({
						message: '文件大小不能超过' + this.maxFileSize + 'kb',
						type: 'error'
					})
					return false
				}

				return true
			},

			/**
			 * 上传文件
			 * @param { Object} params 包含文件的数据
			 */
			fileUploads(params) {
				const file = params.file
				return new Promise((resolve, reject) => {
					const formData = new FormData()
					formData.append('file', file)
					fileApi
						.fileUploadDynamicReturnUrl(formData)
						.then((res) => {
							resolve(res)
							file.upUrl = res
							params.onSuccess()
						})
						.catch((err) => {
							this.$message({
								message: '上传失败：' + err?.message,
								type: 'error'
							})
							reject(err)
							this.uploadStatus = 'warning'
						})
				})
			},

			// 上传
			cUploads(params) {
				// 先手动移除校验
				// this.$refs.formData.clearValidate('imgId');

				this.fileUploads(params)
					.then((res) => {
						if (!this.formData.imgId) this.formData.imgId = {}
						this.formData.imgId[params.file.uid] = res
					})
					.catch(() => {
						this.$refs.fileUploads.uploadFiles.splice(this.$refs.fileUploads.uploadFiles.indexOf(params.file), 1)
					})
			},
			// 移除
			cRemoves(file) {
				if (this.formData.imgId) {
					delete this.formData.imgId[file.uid]
				}
			},
			// 图片预览
			handlePictureCardPreview(file) {
				this.showViewer = true
				this.previewSrcList = Object.values(this.formData.imgId)
				this.initialIndex = this.previewSrcList.indexOf(file.upUrl || file.raw.upUrl)
			},
			// 关闭预览
			closeViewer() {
				this.showViewer = false
			},
			// 附件反显处理
			setFileValue(imgs) {
				if (imgs && imgs !== '') {
					this.fileList = imgs.split(',').map((url, index) => {
						const uid = `reback_${index}`

						if (!this.formData.imgId) this.formData.imgId = {}
						this.formData.imgId[uid] = url
						return { uid, url, upUrl: url, name: url.slice(url.lastIndexOf('/') + 1) }
					})
				}
			},

			// 渲染
			renderTitle1() {
				return [
					{
						module: 'Select',
						label: '我的部门',
						prop: 'depart',
						option: this.departmentOption,
						bindObject: (obj) => {
							this.formData.departObj = obj.objOption
						}
					},
					{ module: 'Select', label: '收款抬头', prop: 'receiveTitle', option: this.paymentOption }
				]
			},
			renderTitle2(index) {
				const setOrderDetail = (key, value) => {
					this.formData.orderDetail[index][key] = value
				}
				const isHideAccount = this.formData.orderDetail[index].isHideAccount

				return [
					{
						module: 'Cascader',
						label: '服务内容',
						prop: 'business',
						option: this.businessOption,
						span: 24,
						bindObject: (obj) => {
							if (obj) {
								let businessCodeDetailId = null
								;['businessDisk', 'businessCode', 'businessCodeDetail'].forEach((key, keyIndex) => {
									setOrderDetail(`${key}Id`, obj.value[keyIndex])
									setOrderDetail(`${key}Name`, obj.label[keyIndex])
									if (keyIndex === 2) businessCodeDetailId = obj.value[keyIndex]
								})

								const isHide = !this.canuseBusinessCode.includes(businessCodeDetailId)
								setOrderDetail('isHideAccount', isHide)
							}
						}
					},
					{ module: 'InputNumber', label: '金额', prop: 'businessPrice', maxlength: 20 },
					{ module: 'InputNumber', label: '成本金额', prop: 'cost', maxlength: 20 },
					{ module: 'InputNumber', label: '代帐月份', prop: 'accountMonth', maxlength: 20, ifHidden: isHideAccount },
					{
						module: 'Select',
						label: '代帐性质',
						prop: 'accountProperties',
						option: this.accountPropertiesOption,
						ifHidden: isHideAccount
					},
					{
						module: 'Select',
						label: '代帐城市',
						prop: 'accountCityId',
						option: this.accountCityOption,
						ifHidden: isHideAccount,
						bindObject: (obj) => {
							setOrderDetail('accountCity', obj.label)
						}
					},
					{
						module: 'batch',
						label: '',
						prop: 'orderSalesman',
						children: [
							{ module: 'ClickSelect', label: '分润人', prop: 'userName' },
							{ module: 'InputNumber', label: '分润金额', prop: 'achievement', maxlength: 20 }
						]
					}
				]
			},
			renderTitle3() {
				const {
					isHideCluesSources,
					isHidePhoneAndDate,
					isHideClueDivider,
					isHideYMD,
					isHideBeforeSalesperson,
					isHideIntroducerCompany,
					isHideAccountDept
				} = this.hideAttrs

				return [
					{ module: 'Select', label: '签单类型', prop: 'type', option: this.typeOption },
					{ module: 'Select', label: '签约方式', prop: 'contractWay', option: this.contractWayOption },
					{
						module: 'Select',
						label: '来源',
						prop: 'orderSourceId',
						option: this.orderSourceOption,
						bindObject: (obj) => {
							this.formData.orderSourceName = obj.label
						}
					},

					{
						module: 'ClickSelect',
						label: '线索来源',
						prop: 'cluesSourcesName',
						ifHidden: isHideCluesSources,
						span: 24
					},
					{
						module: 'batch',
						label: '',
						prop: 'clueDivider',
						children: [
							{ module: 'ClickSelect', label: '线索分润人', prop: 'cluesShareName' },
							{ module: 'InputNumber', label: '线索分润业绩', prop: 'cluesShareAchievement', maxlength: 20 }
						],
						ifHidden: isHideClueDivider
					},

					{
						module: 'Input',
						label: '客户手机号码',
						prop: 'customerMobile',
						maxlength: 20,
						ifHidden: isHidePhoneAndDate
					},
					{ module: 'DatePicker', label: '资源日期', prop: 'resourceDate', ifHidden: isHidePhoneAndDate },
					{
						module: 'Input',
						label: '原销售',
						prop: 'beforeSalesperson',
						maxlength: 20,
						ifHidden: isHideBeforeSalesperson
					},
					{
						module: 'Input',
						label: '介绍公司编号',
						prop: 'introducerCompany',
						maxlength: 20,
						ifHidden: isHideIntroducerCompany
					},
					{ module: 'Input', label: '会计部门', prop: 'accountDept', maxlength: 20, ifHidden: isHideAccountDept },
					{
						module: 'InputNumber',
						label: '资源月份',
						prop: 'resourceMonth',
						maxlength: 20,
						ifHidden: isHideAccountDept
					},
					{
						module: 'InputNumber',
						label: '缴费前记账金额',
						prop: 'beforeRenewMoney',
						maxlength: 20,
						ifHidden: isHideAccountDept
					},
					{
						module: 'InputNumber',
						label: '续费前记账月份',
						prop: 'beforeRenewMonth',
						maxlength: 20,
						ifHidden: isHideAccountDept
					},

					{
						module: 'Select',
						label: '活动',
						prop: 'activityId',
						option: this.activityOption,
						bindObject: (obj) => {
							this.formData.activityName = obj.label
						}
					},
					{ module: 'Select', label: '是否优惠', prop: 'preferential', option: this.isNoOption },
					{ module: 'Select', label: '收款类型', prop: 'frontMoney', option: this.frontMoneyOption },
					{ module: 'InputNumber', label: '年', prop: 'year', maxlength: 20, ifHidden: isHideYMD },
					{ module: 'InputNumber', label: '月', prop: 'month', maxlength: 20, ifHidden: isHideYMD },
					{ module: 'InputNumber', label: '日', prop: 'day', maxlength: 20, ifHidden: isHideYMD },
					{ module: 'InputNumber', label: '单号', prop: 'orderNo', maxlength: 20, ifHidden: isHideYMD },

					{ module: 'Select', label: '亮点', prop: 'tags', multiple: true, option: this.tagsOption, span: 24 },
					{ module: 'Textarea', label: '备注', prop: 'remark', maxlength: 200, span: 24 }
				]
			},
			// 表单项
			renderFormItemEl(childItem, bind, formItemProp) {
				const { label, ...other } = childItem
				return (
					<el-form-item
						prop={formItemProp ? formItemProp : childItem.prop}
						label={childItem.label + '：'}
						label-width={childItem.labelWidth}
						rules={this.rules[childItem.prop]}>
						<EntryItems
							module={childItem.module}
							v-model={bind[childItem.prop]}
							disabled={this.isEdit}
							{...{ ...other, 'aria-label': label }}
						/>
					</el-form-item>
				)
			},

			onPopoverScroll() {
				this.visible = false
			}
		},
		render() {
			const formEl = (
				<el-form ref="formRef" label-width="140px" model={this.formData}>
					<div class="sub-title">双方信息</div>
					<ElRow class="content-box">
						{this.renderTitle1().map((item, index) => (
							<ElCol key={index} span={this.isEdit?12:8}>
								{this.renderFormItemEl(item, this.formData)}
							</ElCol>
						))}
					</ElRow>

					<div class="sub-title">商品和金额</div>
					{this.formData.orderDetail.map((multiple, index) => (
						<ElRow key={index} class="content-box service-container">
							{!this.isEdit ? (
								<div class="service-button-group">
									{index === 0 ? (
										<el-button
											type="primary"
											text={true}
											size="small"
											onClick={() => this.addItem(this.formData.orderDetail, initDataService())}>
											+ 添加
										</el-button>
									) : null}
									{index !== 0 ? (
										<el-button
											type="primary"
											text={true}
											size="small"
											style="color:red;"
											onClick={() => this.deleteItem(this.formData.orderDetail, index)}>
											- 删除
										</el-button>
									) : null}
								</div>
							) : null}

							{this.renderTitle2(index).map((item, itemIndex) => {
								if (item.ifHidden) return null

								if (item.module === 'batch') {
									return multiple[item.prop].map((multipleChild, multipleChildIndex) => {
										return (
											<ElCol
												key={itemIndex + '_' + multipleChildIndex}
												span={24}
												onClick={(e) => {
													if (e.target.dataset.capture) {
														e.stopPropagation()
														this.checkedIndex = [index, multipleChildIndex]
														const checkedStaff = this.toOrderSalesman(this.checkedIndex).get()
														this.checkedStaff = checkedStaff ? [checkedStaff] : []
														this.visibleStaff = true
													}
												}}>
												{item.children.map((childItem) => (
													<ElCol span={8} class="float-left">
														{this.renderFormItemEl(
															childItem,
															multipleChild,
															'orderDetail.' + index + '.orderSalesman.' + multipleChildIndex + '.' + childItem.prop
														)}
													</ElCol>
												))}

												<ElCol span={8} class="float-left" style="padding:0 10px;">
													{multipleChildIndex !== 0 && !this.isEdit ? (
														<el-button
															type="danger"
															icon="el-icon-Close"
															circle
															onClick={() => this.deleteItem(multiple[item.prop], multipleChildIndex)}></el-button>
													) : null}
													{multipleChildIndex === 0 && !this.isEdit ? (
														<el-button
															icon="el-icon-Plus"
															circle
															onClick={() => {
																const d = initDataService()
																this.addItem(multiple[item.prop], d[item.prop][0])
															}}></el-button>
													) : null}
												</ElCol>
											</ElCol>
										)
									})
								}

								return (
									<ElCol key={itemIndex} span={item.span || 8}>
										{this.renderFormItemEl(item, multiple, 'orderDetail.' + index + '.' + item.prop)}
									</ElCol>
								)
							})}
						</ElRow>
					))}

					<div class="sub-title mt10">绩效信息</div>
					<ElRow class="content-box">
						{this.renderTitle3().map((item, itemIndex) => {
							if (item.ifHidden) return null

							if (item.module === 'batch') {
								const multiple = this.formData[item.prop]
								return multiple.map((multipleChild, multipleChildIndex) => {
									return (
										<ElCol
											key={itemIndex + '_' + multipleChildIndex}
											span={24}
											onClick={(e) => {
												if (e.target.dataset.capture) {
													e.stopPropagation()
													this.checkedIndex = [multipleChildIndex]
													const checkedStaff = this.toClueDivider(this.checkedIndex).get()
													this.checkedStaff = checkedStaff ? [checkedStaff] : []
													this.visibleStaff = true
												}
											}}>
											{item.children.map((childItem, index) => (
												<ElCol key={index} span={8} class="float-left">
													{this.renderFormItemEl(
														childItem,
														multipleChild,
														'clueDivider.' + multipleChildIndex + '.' + childItem.prop
													)}
												</ElCol>
											))}

											<ElCol span={8} class="float-left" style="padding:0 10px;">
												{multipleChildIndex !== 0 && !this.isEdit ? (
													<el-button
														type="danger"
														icon="el-icon-Close"
														circle
														onClick={() => this.deleteItem(multiple, multipleChildIndex)}></el-button>
												) : null}
												{multipleChildIndex === 0 && !this.isEdit ? (
													<el-button
														icon="el-icon-Plus"
														circle
														onClick={() => {
															this.addItem(multiple, initDataClueDivider())
														}}></el-button>
												) : null}
											</ElCol>
										</ElCol>
									)
								})
							}

							return (
								<ElCol
									key={itemIndex}
									span={item.span || 8}
									onClick={(e) => {
										if (e.target.dataset.capture) {
											e.stopPropagation()
											this.checkedIndex = 0
											const checkedStaff = this.toClueSource().get()
											this.checkedStaff = checkedStaff ? [checkedStaff] : []
											this.visibleStaff = true
										}
									}}>
									{this.renderFormItemEl(item, this.formData)}
								</ElCol>
							)
						})}
					</ElRow>

					{/* 附件 */}
					<div class="sub-title mt10">付款明细</div>
					<ElRow class="content-box">
						{this.isEdit ? (
							<div class="image__preview">
								{this.fileList.length
									? this.fileList.map((item) => {
											return (
												<el-image
													key={item.url}
													src={item.url}
													fit="cover"
													style="cursor: pointer;width:100px;height:100px;margin-left:8px;"
													preview-src-list={Object.values(this.formData.imgId)}></el-image>
											)
									  })
									: null}
							</div>
						) : (
							<el-upload
								ref="fileUploads"
								class="upload-demo"
								style="margin-left:20px;"
								action=""
								accept="image/jpg,image/jpeg,image/png"
								limit={10}
								disabled={this.isEdit}
								on-exceed={() => {
									this.$message.warning('最多选择10个文件')
								}}
								multiple
								http-request={this.cUploads}
								file-list={this.fileList}
								before-upload={this.beforeFileUploads}
								onPreview={this.handlePictureCardPreview}
								onRemove={this.cRemoves}
								list-type="picture-card">
								<el-icon>
									<el-icon-Plus />
								</el-icon>
							</el-upload>
						)}
					</ElRow>
				</el-form>
			)

			const tipEl = (
				<div style="color:red; margin-top:20px;">
					<p>注意：请勿重复创建台账！</p>
					{/*
					<p>当选择线下签约并收款，填写上述信息，点击完成后即可创建台账；</p>
					<p>当选择线上签约并支付，待合同签署且支付后，点击对应合同的【操作-报单信息表】创建台账；</p>
					<p>当选择线上签约不支付，填写上述信息，待合同签署且财务审核后，自动创建台账。</p>
					*/}
				</div>
			)
			return (
				<div class="customsDeclaration-component">
					{/* 表单信息 */}
					{formEl}

					{/* 提示语 */}
					{tipEl}

					{/* 附件预览 */}
					<base-image-viewer
						visible={this.showViewer}
						initial-index={this.initialIndex}
						url-list={this.previewSrcList}
						onClose={this.closeViewer}
					/>
					{/* 选人 */}
					<select-deps-staff-QW
						append-to-body
						visible={this.visibleStaff}
						checked={this.checkedStaff}
						onUpdate:checked={(val) => {
							this.checkedStaff = val
							if (this.checkedIndex.length) {
								this[this.checkedIndex.length > 1 ? 'toOrderSalesman' : 'toClueDivider'](this.checkedIndex).set(val)
							} else {
								this.toClueSource().set(val)
							}
						}}
						onCancel={() => {
							this.visibleStaff = false
						}}
					/>

					{/* 按钮 */}
					{this.isEdit ? null : (
						<div style="text-align:center;">
							<el-popover placement="top" width="420" trigger="click" v-model:visible={this.visible}>
								{{
									default: () => (
										<div>
											<p style="font-weight:600;font-size:16px;">
												提示：保存后，只能在报单系统后台修改已生成的台账，确认保存吗？
											</p>
											{tipEl}
											<div style="text-align: right; margin: 0">
												<el-button
													type="primary"
													text={true}
													onClick={() => {
														this.visible = false
													}}>
													取消
												</el-button>
												<el-button
													type="primary"
													onClick={() => {
														this.save()
														this.visible = false
													}}>
													确定
												</el-button>
											</div>
										</div>
									),
									reference: () => <el-button type="primary"> 完 成 </el-button>
								}}
							</el-popover>
						</div>
					)}
					{/* 蒙版 */}
					{this.isRelationQW ? null : <div class="relationQW-tips">该账号未关联企业微信！</div>}
				</div>
			)
		}
	}
</script>
<style lang="less" scoped>
	.customsDeclaration-component {
		height: 75vh;
		overflow: auto;
		padding-right: 4px;
		.el-row {
			display: flex;
			flex-wrap: wrap;
		}

		.sub-title {
			font-weight: 600;
			margin-bottom: 10px;
		}

		.service-container {
			position: relative;
			margin-top: 20px;
			border: 1px solid #e5e5e5;
			border-radius: 4px;
			padding: 10px 0;
			.service-button-group {
				position: absolute;
				top: -25px;
				right: 0;
			}
		}

		.relationQW-tips {
			position: absolute;
			top: 55px;
			left: 0;
			background-color: rgba(0, 0, 0, 0.7);
			width: 100%;
			height: calc(100% - 55px);
			z-index: 99;
			font-size: 24px;
			text-align: center;
			padding-top: 35vh;
			color: #f56c6c;
		}
	}
</style>
